package top.dreamcenter.rss.rsssolverweb.util;


import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * 插件自动任务注册
 */
@Component
public class ScheduleHelper {

    private final Map<String, ScheduledFuture<?>> taskMap = new ConcurrentHashMap<>();

    private final ThreadPoolTaskScheduler syncScheduler;

    public ScheduleHelper(ThreadPoolTaskScheduler syncScheduler) {
        this.syncScheduler = syncScheduler;
    }

    /**
     * 注册插件自动任务
     * @param spiderHelper
     */
    public void registerSchedule(SpiderHelper spiderHelper) {

        String route = spiderHelper.getRoute();

        if (taskMap.get(route) != null) {
            stopSchedule(route);
        }

        ScheduledFuture<?> scheduledFuture = syncScheduler.schedule(spiderHelper, new CronTrigger(spiderHelper.getCron()));
        taskMap.put(route, scheduledFuture);
    }

    /**
     * 删除自动任务
     * @param route
     * @return
     */
    public boolean stopSchedule(String route) {

        if (!taskMap.containsKey(route)) return false;

        ScheduledFuture<?> scheduledFuture = taskMap.get(route);
        scheduledFuture.cancel(true);
        taskMap.remove(route);

        return true;
    }


}
